import Glibc

class Timer {
    private let CLOCK_REALTIME = 0
    private var start_timespec = timespec()
    private var end_timespec = timespec()
    private var time_spec = timespec()
    func start() {
        clock_gettime(Int32(CLOCK_REALTIME),&start_timespec)
    }
    
    func stop() -> Double {
        clock_gettime(Int32(CLOCK_REALTIME),&end_timespec)
        let start_time = Double(start_timespec.tv_sec * 1_000_000 + start_timespec.tv_nsec / 1_000)
        let end_time = Double(end_timespec.tv_sec * 1_000_000 + end_timespec.tv_nsec / 1_000)
        let time = end_time - start_time
        return time / 1_000
    }
    func getTime() -> Double {
        clock_gettime(Int32(CLOCK_REALTIME),&time_spec)
        return Double(time_spec.tv_sec * 1_000_000 + time_spec.tv_nsec / 1_000)
    }
}

let timer = Timer()

class Obj {
    var num: Int
    init (_ num: Int) {
        self.num = num;
    }
}

func AllocateObj() {
    let count = 100000;
    var data: [Obj] = [Obj(1), Obj(1), Obj(1), Obj(1), Obj(1)];
    let resources: [Int] = [12, 43, 56, 76, 89, 54, 45, 32, 35, 47, 46, 44, 21, 37, 84];
    let resourcesLength = resources.count - 1;
    timer.start();
    for i in 0..<count {
        if ((resources[i & resourcesLength] & 1) == 0) {
            data[i & 4] = Obj(i);
        } else {
            data[i & 4] = Obj(i - 5);
        }
    }
    let time = timer.stop();
    var res = 0;
    for i in 0..<data.count {
        res += data[i].num;
    }
    print("Allocate Obj :\t\(time)\tms");
}
AllocateObj();
